package com.gdssoft.pdaweb.action.am;

/*
 *  捷达世软件（深圳）有限公司
 *  Copyright (C) 2008-2010 ShenZhen JieDaShi Software Limited Company.
 */
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javassist.bytecode.Descriptor.Iterator;

import javax.annotation.Resource;

import com.gdssoft.core.command.QueryFilter;
import com.gdssoft.core.util.BeanUtil;
import com.gdssoft.core.util.ContextUtil;
import com.gdssoft.core.util.DateUtil;
import com.gdssoft.core.web.action.BaseAction;
import com.gdssoft.framework.model.system.AppUser;
import com.gdssoft.framework.service.system.DepartmentService;
import com.gdssoft.pdaweb.model.am.AmPlan;
import com.gdssoft.pdaweb.model.am.PdaAmMeter;
import com.gdssoft.pdaweb.model.am.PdaAmMeterList;
import com.gdssoft.pdaweb.model.water.PdaWaterList;
import com.gdssoft.pdaweb.service.am.PdaAmMeterListService;
import com.gdssoft.pdaweb.service.am.PdaAmMeterService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import flexjson.JSONSerializer;

/**
 * 
 * @author
 * 
 */
public class PdaAmMeterListAction extends BaseAction {
	@Resource
	private PdaAmMeterListService pdaAmMeterListService;
	@Resource
	private PdaAmMeterService pdaAmMeterService;
	@Resource
	private DepartmentService departmentService;

	private Long id;
	private File file;
	private String fileFileName;
	private String fileName;
	private String filePath;
	private String importMonth;
	private PdaAmMeterList pdaAmMeterList;

	public String getImportMonth() {
		return importMonth;
	}

	public void setImportMonth(String importMonth) {
		this.importMonth = importMonth;
	}

	public PdaAmMeterListService getPdaAmMeterListService() {
		return pdaAmMeterListService;
	}

	public void setPdaAmMeterListService(
			PdaAmMeterListService pdaAmMeterListService) {
		this.pdaAmMeterListService = pdaAmMeterListService;
	}

	public PdaAmMeterService getPdaAmMeterService() {
		return pdaAmMeterService;
	}

	public void setPdaAmMeterService(PdaAmMeterService pdaAmMeterService) {
		this.pdaAmMeterService = pdaAmMeterService;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public PdaAmMeterList getPdaAmMeterList() {
		return pdaAmMeterList;
	}

	public void setPdaAmMeterList(PdaAmMeterList pdaAmMeterList) {
		this.pdaAmMeterList = pdaAmMeterList;
	}

	/**
	 * 导入文件
	 * 
	 * @return
	 */
	public String saveExcel() {
		
		List<PdaAmMeterList> errorList = pdaAmMeterListService.checkXLSFormat(
				importMonth, file);
		StringBuffer buff = new StringBuffer(
				"{\"success\":true,\"totalCounts\":");

		if (errorList.size() == 0) {
			int count = pdaAmMeterListService.saveExcel(importMonth, file);
			buff.append(count);
			buff.append(",\"flag\": 0");
		} else {
			buff.append(errorList.size());
			JSONSerializer serializer = new JSONSerializer();
			buff.append(",\"flag\": 1");
			buff.append(",\"result\":");
			buff.append(serializer.exclude(new String[] { "class" }).serialize(
					errorList));
		}
		buff.append("}");
		jsonString = buff.toString();
		return SUCCESS;
	}

	// 导出
	public void exportExcel() {
		if (!pdaAmMeterList.getMonth().isEmpty()) {
			AppUser appUser = ContextUtil.getCurrentUser();
			PdaAmMeterList pl = new PdaAmMeterList();
			pl.setMonth(pdaAmMeterList.getMonth());
			String deptId = departmentService.getSubDepIds();
			pdaAmMeterListService.excelExport(getResponse(), pdaAmMeterList,
					appUser.getUsername(),deptId);
		}
	}

	/**
	 * 显示列表
	 */
	public String query() {
		List<PdaAmMeterList> meterList = new ArrayList<PdaAmMeterList>();
		int count = 0;
		if (pdaAmMeterList != null) {
			count = pdaAmMeterListService.queryCount(pdaAmMeterList);
			if (getStart() < count) {
				int to = getStart() + getLimit();
				meterList = pdaAmMeterListService.query(pdaAmMeterList,
						getStart(), to > count ? count : to);
			}
		}
		JSONSerializer serializer = new JSONSerializer();
		StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
				.append(count).append(",result:");
		buff.append(serializer.exclude(new String[] { "class" }).serialize(
				meterList));
		buff.append("}");

		jsonString = buff.toString();
		return SUCCESS;
	}

	/**
	 * 显示列表
	 */
	public String list() {
		String depIds = departmentService.getSubDepIds();
		Map paramsMap = getRequest().getParameterMap();
		Map params = new HashMap();
		for(Object str : paramsMap.keySet()){
			String []as = (String[])paramsMap.get((String)str);
			if(as.length>0)params.put((String)str,as[0]);
		}
		String ss = (String)params.get("Q_status_S_SIN");
		if(ss != null && !ss.isEmpty())for(String s:ss.split(",")) Integer.parseInt(s);//check isNum
				
		List<PdaAmMeterList> list = pdaAmMeterListService.getList(params,depIds);
		int count = pdaAmMeterListService.getListCount(params,depIds);
		
		JSONSerializer serializer=new JSONSerializer();
		StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
		.append(count).append(",result:");		
        buff.append(serializer.exclude(new String[] { "class" }).serialize(list));
		buff.append("}");
		
		jsonString=buff.toString();	
		
		return SUCCESS;
	}

	/**
	 * 顯示列表
	 */
	public String searchList() {
		String mIds = getSubMeterIds();
		if (!mIds.isEmpty()) {
			QueryFilter filter = new QueryFilter(getRequest());
			filter.addFilter("Q_pdaAmMeter.amId_S_SIN", mIds);// 只查当前用户权限下的管理处
			List<PdaAmMeterList> list = pdaAmMeterListService
					.getSearchList(filter);
			List<PdaAmMeterList> list1 = new ArrayList<PdaAmMeterList>();
			for (int i = 0; i < list.size(); i++) {
				list.get(i).setLastDegree(
						pdaAmMeterListService.getPdaAmMeterList(list.get(i)));
			}

			JSONSerializer serializer = new JSONSerializer();
			StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
					.append(filter.getPagingBean().getTotalItems()).append(
							",result:");
			buff.append(serializer.exclude(new String[] { "class" }).serialize(
					list));
			buff.append("}");

			jsonString = buff.toString();
		} else {
			jsonString = "{success:false}";
		}
		return SUCCESS;

	}

	/**
	 * 显示详细信息
	 * 
	 * @return
	 */
	public String get() {
		PdaAmMeterList pdaAmMeterList = pdaAmMeterListService.get(id);

		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
		// 将数据转成JSON格式
		StringBuffer sb = new StringBuffer("{success:true,data:");
		sb.append(gson.toJson(pdaAmMeterList));
		sb.append("}");
		setJsonString(sb.toString());

		return SUCCESS;
	}

	/**
	 * 添加及保存操作
	 */
	public String save() {
		AppUser au = ContextUtil.getCurrentUser();
		String updateDate = DateUtil.dateFormat(new Date(), "yyyy-MM-dd");
		pdaAmMeterList.setLasteditby(au.getUsername());
		pdaAmMeterList.setLasteditdt(updateDate);
		pdaAmMeterList.setUpdataid(au.getUsername());
		pdaAmMeterList.setUpdatedate(updateDate);

		if (pdaAmMeterList.getId() == null) {
			try {
				pdaAmMeterListService.save(pdaAmMeterList);
			} catch (Exception e) {
				logger.error("SAVE pdaAmMeterList ERROR:" + e.getMessage());
			}
		} else {
			PdaAmMeterList orgPdaAmMeterList = pdaAmMeterListService
					.get(pdaAmMeterList.getId());
			String status = pdaAmMeterListService.checkNomal(
					orgPdaAmMeterList.getAmId(), pdaAmMeterList.getDegree(),
					orgPdaAmMeterList.getMonth());
			pdaAmMeterList.setStatus(status);
			pdaAmMeterList.setTranscribeType(1);
			pdaAmMeterList.setRecorderId(au.getUsername());
			try {
				BeanUtil.copyNotNullProperties(orgPdaAmMeterList,
						pdaAmMeterList);
				pdaAmMeterListService.save(orgPdaAmMeterList);
			} catch (Exception ex) {
				logger.error(ex.getMessage());
			}
		}
		setJsonString("{success:true}");
		return SUCCESS;
	}

	public String check() {
		String ids = fileName.trim();
		if (ids.endsWith(",")) {
			ids = ids.substring(0, ids.length() - 1);
		}
		if (ids.contains("'")) {
			setJsonString("{success:false}");
		} else {
			String status = "1"; // 通过
			setJsonString("{success:"
					+ pdaAmMeterListService.check(ids, status) + "}");
		}

		return SUCCESS;
	}

	/**
	 * 修正
	 */
	public String saveFixedUsage() {
		jsonString = "{success:"
				+ pdaAmMeterListService.saveFixedUsage(pdaAmMeterList) + "}";
		return SUCCESS;
	}

	/**
	 * 顯示計劃列表
	 */
	public String planList() {
		QueryFilter filter = new QueryFilter(getRequest());
		String month = getRequest().getParameter("Q_month_S_EQ");
		String planName = getRequest().getParameter("Q_planName_S_LK");
		String executor = getRequest().getParameter("Q_executor_S_LK");
		String dptId = departmentService.getSubDepIds();
		List<AmPlan> planList = pdaAmMeterListService.getPlanList(month,
				planName, executor, dptId, filter);
		for (int i = 0; i < planList.size(); i++) {
			if (planList.get(i).getPlanStatus() == 3
					|| planList.get(i).getPlanStatus() == 4) {
				Long planId = planList.get(i).getPlanId();
				String mon = planList.get(i).getLastEditBy();
				List<PdaAmMeterList> amList = pdaAmMeterListService
						.checkStatus(planId, mon);
				if (amList.size() > 0 && amList != null) {
					planList.get(i).setPlanStatus(2l);
				}
			}
		}
		JSONSerializer serializer = new JSONSerializer();
		StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
				.append(pdaAmMeterListService.getPlanListNum(month, planName,
						executor, dptId)).append(",result:");
		buff.append(serializer.exclude(new String[] { "class" }).serialize(
				planList));
		buff.append("}");

		jsonString = buff.toString();
		return SUCCESS;
	}

	/**
	 * 按照計劃審核
	 * 
	 * @return
	 */
	public String checkPlan() {
		String ids = fileName.trim();
		String month = getRequest().getParameter("Q_month_S_EQ");
		if (ids.endsWith(",")) {
			ids = ids.substring(0, ids.length() - 1);
		}
		if (ids.contains("'")) {
			setJsonString("{success:false}");
		} else {
			String status = "1"; // 通过
			boolean ynOk = pdaAmMeterListService.checkPlan(ids, status, month);
			setJsonString("{success:" + ynOk + "}");
		}

		return SUCCESS;
	}

	/**
	 * 审核明细查询
	 */
	public String checkDetailSearch() {
		QueryFilter filter = new QueryFilter(getRequest());
		String planId = getRequest().getParameter("Q_planId_S_EQ");
		String planName = getRequest().getParameter("Q_planName_S_EQ");
		String month = getRequest().getParameter("Q_month_S_EQ");
		String executor = "";// getRequest().getParameter("Q_executor_S_EQ");
		String fangId = getRequest().getParameter("aparmentId_S_LK");
		String waterId = getRequest().getParameter("Q_amId_S_LK");
		String dongId = getRequest().getParameter("buildingId_S_LK");
		String quId = getRequest().getParameter("districtId_S_LK");
		String depId = departmentService.getSubDepIds();
		List<PdaAmMeterList> list = pdaAmMeterListService.getCheckDetailSearch(
				planId, planName, month, executor, fangId, waterId, dongId,
				quId, depId, filter);
		List<PdaAmMeterList> list1 = new ArrayList<PdaAmMeterList>();
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).getStatus().equals("0")) {
				list.get(i).setRemark("待审核");
			} else if (list.get(i).getStatus().equals("2")) {
				list.get(i).setRemark("这个月读数小于上个月读数");
			} else if (list.get(i).getStatus().equals("3")) {
				list.get(i).setRemark("本月读数大于上月与去年同月读数平均數的10%");
			} else if (list.get(i).getStatus().equals("4")) {
				list.get(i).setRemark("换表");
			} else {
				list.get(i).setRemark("");
			}
			list.get(i).setCreateddt(planName);
			list.get(i).setLastDegree(
					pdaAmMeterListService.getPdaAmMeterList(list.get(i)));
		}
		JSONSerializer serializer = new JSONSerializer();
		StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
				.append(pdaAmMeterListService.getCheckDetailSearchNumb(planId,
						planName, month, executor, fangId, waterId, dongId,
						quId, depId)).append(",result:");
		buff.append(serializer.exclude(new String[] { "class" })
				.serialize(list));
		buff.append("}");

		jsonString = buff.toString();
		return SUCCESS;
	}

	/**
	 * 获取当前用户下属的未删除所有电表的id
	 * 
	 * @return 如"101,12,15"
	 */
	private String getSubMeterIds() {
		String ids = "";
		QueryFilter filter = new QueryFilter(0, Integer.MAX_VALUE);
		filter.addFilter("Q_department.depId_S_LIN",
				departmentService.getSubDepIds());// 只查当前用户权限下的管理处
		List<PdaAmMeter> mlist = pdaAmMeterService.getAll(filter);
		ids = "";
		if (mlist.size() > 0) {
			for (PdaAmMeter pdaAmMeter : mlist) {
				ids += pdaAmMeter.getAmId() + ",";
			}
			ids = ids.substring(0, ids.length() - 1);
		}
		return ids;
	}

}
